package finalProject;
import java.util.ArrayList;
import java.util.List;

import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.AsUndirectedGraph;
import org.jgrapht.graph.DefaultDirectedGraph;


public class Tree {

	private DefaultDirectedGraph<Token, TokensEdge> tree;
	private AsUndirectedGraph<Token, TokensEdge> undirectedGraph;

	public Tree (ArrayList<Token> tokens){
		tree = new DefaultDirectedGraph<Token, TokensEdge>(TokensEdge.class);
		// add vertices
		for (Token token : tokens) {
			tree.addVertex(token);
		}
		//create edges
		for (Token token : tokens) {
			if (token.getHeadIndex() != 0){
				tree.addEdge(tokens.get(token.getHeadIndex()-1),token);
			}
		}	
		undirectedGraph = new AsUndirectedGraph<Token, TokensEdge>(tree);
	}

	public String getPath(Token source , Token target){
		StringBuilder ans = new StringBuilder() ;
		DijkstraShortestPath<Token, TokensEdge> dij = new DijkstraShortestPath<Token, TokensEdge>(this.undirectedGraph, source, target);
		List<TokensEdge> path = dij.getPathEdgeList();
		if (path != null){
			TokensEdge firstEdgeWithRoot = findRootInPath(path);
			if(firstEdgeWithRoot != null){
				boolean foundRootEdge = path.get(0).equals(firstEdgeWithRoot);
				if(foundRootEdge && path.size() > 1)
				{
					if(path.get(1).sourceVertex().getHeadIndex() == 0)
						foundRootEdge = false;
				}
//				for (TokensEdge tokensEdge : path) {
				for (int i = 0; i < path.size(); i++) {
					TokensEdge tokensEdge = path.get(i);
					Token s = tokensEdge.sourceVertex();
					Token t = tokensEdge.targetVertex();
					if (!foundRootEdge){
						if (i != 0) {
							ans.append(t.getWord());
							ans.append(":");
						}
						ans.append(t.getPosTag());
						ans.append(":");
						ans.append(t.getDepLabel());
						ans.append(":");
						ans.append(s.getPosTag());
//						ans.append(":");
//						ans.append(s.getWord());
						if (i != path.size() - 1) {
							ans.append(":");
							ans.append(s.getWord());
						}
					}
					else{
						if (i != 0) {
							ans.append(s.getWord());
							ans.append(":");
						}
						ans.append(s.getPosTag());
						ans.append(":");
						ans.append(t.getDepLabel());
						ans.append(":");
						ans.append(t.getPosTag());
						if (i != path.size() - 1) {
							ans.append(":");
							ans.append(t.getWord());
						}
					}
					if (i != path.size() - 1) {
						ans.append(",");
					}
					if (tokensEdge.equals(firstEdgeWithRoot))
						foundRootEdge = true;
				}
				//ans.delete(0, ans.indexOf(":")+1);
				//ans.delete(ans.lastIndexOf(":"), ans.length());
				return ans.toString();
			}
		}
		return null;

	}

	private TokensEdge findRootInPath(List<TokensEdge> path) {
		for (TokensEdge tokensEdge : path) {
			if (tokensEdge.sourceVertex().getHeadIndex() == 0){
				return tokensEdge;
			}
		}
		return null;
	}



}
